<?php

namespace app\admin\controller\shop\market\coupon;

use app\admin\controller\shop\Base;
use Throwable;

/**
 * 用户领券记录
 */
class Receive extends Base
{
    /**
     * Receive模型对象
     * @var object
     * @phpstan-var \app\admin\model\shop\market\coupon\Receive
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'name', 'create_time'];

    protected string|array $quickSearchField = ['user.nickname'];

    protected array $withJoinTable = [
        'user'   => ['nickname'],
        'coupon' => ['name', 'discount_type', 'discount_amount', 'discount_ratio', 'min_price', 'range_type']
    ];


    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\shop\market\coupon\Receive;
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withTrashed()
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => '删除优惠券领券记录会回收用户已领取的优惠券',
        ]);
    }

    /**
     * 还原
     * @return void
     */
    public function restore(): void
    {
        $id = $this->request->post('id');

        $this->model->startTrans();
        try {
            $records = $this->model->where(['id' => $id])->onlyTrashed()->select();
            foreach ($records as $record) {
                $record->restore();
            }

            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }
        $this->success('还原成功');
    }
}